<template>
    <div id="risk-order-content" class="order-content">
        <!-- 指令相关 -->
        <el-row class="risk-order-top">
            <el-col :span="12" class="form-col col-box">
                <el-row class="form-content">
                    <!-- ETF指令表单 -->
                    <ETFForm
                        :key="renderCountKey"
                        @getOrderForm="getOrderForm(arguments)"
                        @getETFBasicInfo="getETFBasicInfo"
                        @handleRefreshTableState="handleRefreshTableState"
                    />
                </el-row>
                <el-row class="form-operate">
                    <el-col :span="7">
                        <i  name="entrySetting" style="font-size: 25px" class="el-icon-setting iconClass" @click="openEntryGroupDialog"></i>
                    </el-col>
                    <el-col :span="17">
                        <el-button name="reset" @click="handleClickButtonReset">重置</el-button>
                        <el-button name="calculate" type="primary" size="mini" @click="handleETFCalc">计算</el-button>
                        <el-button name="test" type="primary" size="mini" @click="handleTestClick">试算</el-button>
                        <!-- <el-button name="place" type="primary" size="mini" @click="handlePlaceOrderClick">下单</el-button> -->
                    </el-col>
                </el-row>
            </el-col>
            <!-- 成分股信息 -->
            <el-col :span="12" class="col-box">
                <el-tabs type="card" v-model="activePane">
                    <el-tab-pane label="成分股信息" name="1">
                        <ConstituentStockDialog
                            :showDialog="false"
                            :stockDialog="stockDialog"
                            :orderForm="instruction"
                            :etfBasicInfo="etfBasicInfo"
                        />
                    </el-tab-pane>
                </el-tabs>
            </el-col>
        </el-row>

        <!-- 试算结果 -->
        <el-row class="risk-order-bottom">
            <TrailResultPlus :riskResultMsg="trailResultMsg" :tableName="tableName" />
        </el-row>

        <EntryGroupSetting
            v-if="transDialog"
            :resourceCode="resourceCode"
            :transDialog="transDialog"
            @getEntryGroup="getEntryGroup"
            @closeEntryDialog="closeEntryDialog"
        />
        <!--处理下单后的弹窗-->
        <RiskOrderResultAfter
            v-if="orderCancelShow"
            :key="riskOrderResultAfterKey"
            :riskResultThresholdType="result"
            :res="riskOrderResultTable"
            @riskResultContinue="riskResultContinue"
            @riskResultCancel="riskResultCancel"
        />
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import { getActiveMenuCode, getUser } from '@/utils/user-util';
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { SGU_CACHE } from '@/utils/diction-const-util';
import { numberFormat, unitShow, UUID } from '@/utils/tools';
import ColumnUtil from '../utils/column-util';
import ETFColumnUtil from '../utils/etf-column-util';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import EntryGroupSetting from '../components/entry-group-seting.vue';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import RiskOrderResultAfter from '@/pages/risk-time/components/risk-order-result-after.vue';
import { cancelCommonOrder } from '@/common/api/instruction';
import ETFForm from '../components/etf-form.vue';
import moment from 'moment';
import TrailResultPlus from '../components/trail-result-plus.vue';
import RiskTablePlus from '@/common/components/risk-table-plus.vue';
import { TableConfigVO } from '@/common/vo';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import { OrderClass } from '../class/order-class';
import RiskPagination from '@/common/components/risk-pagination.vue';
import { calculateEtfStock, etfOrderCalculate, getEtfStockList } from '../api/etf';
import ConstituentStockDialog from './constituentStock-dialog.vue';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'ETFOrder',
    components: {
        RiskEntryInput,
        RiskTableLayout,
        StatusTag,
        BranchTag,
        EntryGroupSetting,
        RiskInputNumber,
        RiskOrderResultAfter,
        TrailResultPlus,
        RiskTablePlus,
        ETFForm,
        RiskIconButton,
        RiskPagination,
        ConstituentStockDialog,
    },
})
/**
 * ETF指令下单Tab
 */
export default class ETFOrder extends OrderClass {
    ColumnUtil = new ColumnUtil();
    ETFColumnUtil = new ETFColumnUtil();
    numberFormat = numberFormat;
    unitShow = unitShow;

    stockTableData: any = []; // 成分股信息列表
    tableConfig: TableConfigVO = {
        rowKey: 'no', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };

    // 分页
    pages = { currentPage: 1, pageSize: 25, total: 0 };

    // 风控指令表单
    instruction: any = {
        fundCode: '', // 产品代码
        assetCode: '', // 资产单元编码
        assetName: '', // 资产单元名称
        fundAccountCode: '', // 组合编码
        orderDirection: 'P', // 委托方向
        stockCode: '', // 证券代码
        stockNameSt: '', // 证券名称
        reportCode: '', // 申报代码
        marketCode: '', // 交易市场编码
        businessType: '6', // 业务类型
        businClass: '6',
        orderPrice: '', // 指令价格
        orderAmount: '', // 指令数量
        orderBalance: '', // 指令金额
        fundNameSt: '', // 产品简称
        fundAccountName: '', // 组合名称
        targetType: '1', // 目标类型
        investType: '1', // 投资类型
    };

    Invest: any = new Invest(); // 指令相关字典类
    entryType = {}; // 风险类型字典
    compareDirection = {}; // 比较方向字典
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    opponentCodeSelectData: any[] = []; // 交易对手方下拉数据
    stockCodeSelectData: any[] = []; // 证券代码下拉框数据
    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据

    stockTypePojo: any = {};
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态

    // 试算结果信息
    trailResultMsg: any = {
        calcTime: '', // 下单/试算时间
        takeTime: '', // 计算耗时
        riskResult: '', // 风控结果
        riskResultTable: [],
    };
    activePane: string = '1'; // 持仓显示的标签页
    stockTableColumns: any[] = []; //
    stockInfo: any = {};
    tableName: string = 'ETF_ORDER_LAYOUT';
    stockTableCalcState: boolean = false; // ETF成分股表格是否为已计算状态
    summary: any[] = []; // 合计行数据
    footerData: any[] = []; // 表尾合计展示数据
    etfBasicInfo: any = null; // 选中etf的基本信息
    // etf成分券查询表单
    etfStockQueryForm: any = {
        estimatecash: 0,
        execType: '',
        fundCode: '',
        instructionAmount: 0,
        instructionBalance: 0,
        orderDirection: '',
        paging: {
            currentPage: 0,
            pageSize: 0,
        },
        stockCode: '',
        stockTargetType: '',
    };

    // 表单校验字段
    verifyParams: any = {
        fundCode: '产品代码',
        stockCode: '证券代码',
        orderAmount: '指令数量',
        orderBalance: '指令金额',
    };

    async mounted() {
        // 获取当前激活菜单编码
        this.resourceCode = getActiveMenuCode().defaultActive;
        console.log(this.resourceCode, 'this.resourceCode');

        this.getUserSelectEntryGroupList();
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取风险类型字典
        this.entryType = this.Invest.entryType;
        // 获取比较方向字典
        this.compareDirection = this.Invest.CompareDirection;
    }

    /* ******************************* 指令表单相关start ******************************* */

    // 子表单组件 -- 表单获取事件传递
    getOrderForm(args: any) {
        for (const key in args[0]) {
            this.instruction[key] = JSON.parse(JSON.stringify(args[0][key]));
        }
    }

    // 子表单组件事件传递 -- 获取当前选中etf的基本信息
    getETFBasicInfo(args: any) {
        this.etfBasicInfo = args;
        this.etfStockQueryForm = {
            estimatecash: this.etfBasicInfo?.estimatecash || 0,
            execType: this.etfBasicInfo?.execType || '',
            fundCode: this.instruction.fundCode || '',
            instructionAmount: Number(this.instruction.orderAmount) || 0,
            instructionBalance: Number(this.instruction.instructionBalance) || 0,
            orderDirection: this.instruction.orderDirection || '',
            stockCode: this.etfBasicInfo?.stockCode || '',
            stockTargetType: this.instruction.targetType == '1' ? '2' : '1',
        };
        if (args) {
            getEtfStockList(this.etfStockQueryForm).then(res => {
                this.stockTableData = res;
            });
        }
    }

    // 子表单事件传递 -- 跟新表格计算状态事件
    handleRefreshTableState() {
        this.stockTableCalcState = false;
    }

    /* ******************************** 指令表单相关end ******************************* */

    /* *********************** 成分股信息start ********************** */

    /**
     * ETF计算成分股表格
     */
    handleETFCalc() {
        for (const key in this.verifyParams) {
            if (!this.instruction[key]) {
                this.yh_message_warn(this.verifyParams[key] + '不可为空');
                return false;
            }
        }

        if (!this.etfBasicInfo) {
            // 没有选券的时候不调用计算接口
            return;
        }
        let form = {
            estimatecash: this.etfBasicInfo?.estimatecash || 0,
            execType: this.etfBasicInfo?.execType || '',
            fundCode: this.instruction.fundCode || '',
            instructionAmount: Number(this.instruction.orderAmount) || 0,
            instructionBalance: Number(this.instruction.instructionBalance) || 0,
            orderDirection: this.instruction.orderDirection || '',
            stockCode: this.etfBasicInfo?.stockCode || '',
            stockTargetType: this.instruction.targetType == '1' ? '2' : '1',
        };
        calculateEtfStock(form)
            .then(res => {
                this.stockTableData = res;
                this.stockTableCalcState = true;
                this.pages.total = res?.length;
                this.yh_message_success('计算完成');
            })
            .catch(() => {
                this.stockTableData = [];
                this.stockTableCalcState = false;
                this.pages.total = 0;
            });
    }

    /* *********************** 成分股信息end ********************** */

    /* ******************** 试算、下单处理start *********************** */
    /**
     * 校验指令表单
     */
    handleVerifyParam(instruction) {
        let verifyExtra = true;
        let nowDate = moment().format('YYYYMMDD');
        if (String(this.etfBasicInfo?.fileDate || 0) !== nowDate) {
            this.yh_message_warn('ETF成分股不是最新日期，不允许下达！');
            verifyExtra = false;
        }
        let flag = false;
        if (instruction.orderDirection == 'Q') {
            if (!this.stockTableData.length) {
                this.yh_message_warn('所选基金没有对应成分股');
                return false;
            }
            for (let index = 0; index < this.stockTableData.length; index++) {
                const ele = this.stockTableData[index];
                if (ele.actualRedeemAmount > ele.availableAmount) {
                    this.yh_message_warn(
                        '赎回数量' +
                            ele.actualRedeemAmount +
                            '（单位份额' +
                            ele.stockAmount +
                            '）大于可用数量' +
                            ele.availableAmount +
                            '，请重新输入！'
                    );
                    flag = true;
                    break;
                }
            }
        }
        if (flag) {
            verifyExtra = false;
        }
        return verifyExtra;
    }

    /**
     * 生成完整的指令表单（传参表单）
     *  @param instruction 指令表单
     */
    handleCreateInstruction(instruction: any) {
        instruction.instructionType = '19';
        instruction.orderUser = getUser().userCode;
        instruction.outerOrderCode = UUID() + '-' + new Date().getTime();
        instruction.requestId = UUID() + '-' + new Date().getTime();
        instruction.directMode = '8'; // 计算模式为 无序非从严合并计算
        instruction.calculateEntryGroup = this.selectEntryGroupCode.calculateEntryGroup; // 计算条目组
        instruction.excludeEntryGroup = this.selectEntryGroupCode.excludeEntryGroup; // 排除条目组
        instruction.marketCode = this.etfBasicInfo.marketCode;
        instruction.execType = this.etfBasicInfo.execType;
        instruction.reportCode = instruction.stockCode.split(' ')[0] || '';
        instruction.etfStockListInfoDTOList = this.stockTableData;
        instruction.orderBalance = instruction.orderBalance * 10000; // 按最小单位元传给后端
        return instruction;
    }

    // 重置按钮点击事件
    handleClickButtonReset() {
        this.renderCountKey++;
        this.etfBasicInfo = null;
        this.stockTableCalcState = false;
        this.instruction = {
            fundCode: '', // 产品代码
            assetCode: '', // 资产单元编码
            assetName: '', // 资产单元名称
            fundAccountCode: '', // 组合编码
            orderDirection: 'P', // 委托方向
            stockCode: '', // 证券代码
            stockNameSt: '', // 证券名称
            reportCode: '', // 申报代码
            marketCode: '', // 交易市场编码
            businessType: '6', // 业务类型
            businClass: '6',
            orderPrice: '', // 指令价格
            orderAmount: '', // 指令数量
            orderBalance: '', // 指令金额
            fundNameSt: '', // 产品简称
            fundAccountName: '', // 组合名称
            targetType: '1', // 目标类型
            investType: '1', // 投资类型
        };
        // this.$emit('reset', null);
    }
    // 指令表单提交事件
    handleSubmit(orderType: string) {
        // 表单校验
        const verify: any = this.handleVerifyParam(this.instruction);
        if (!verify) {
            return;
        }
        this.instruction = this.handleCreateInstruction(this.instruction);
        this.instruction.orderType = orderType;
        const start = window.performance.now();
        this.trailResultMsg.calcTime = moment().format('YYYY-MM-DD HH:mm:ss');
        etfOrderCalculate(this.instruction).then(res => {
            const end = window.performance.now();
            this.trailResultMsg.takeTime = ((end - start) / 1000).toFixed(3) + '秒'; // 计算耗时
            this.trailResultMsg.riskResult = res.thresholdType;
            const data = res.resultList || [];

            // 根据产品代码 匹配产品名称
            data.forEach(ele => {
                ele.requestId = res.requestId;
                ele.fundNameSt = this.instruction.fundNameSt;
                ele.stockNameSt = this.instruction.stockNameSt;
            });
            this.trailResultMsg.riskResultTable = JSON.parse(JSON.stringify(data));

            if (orderType == '1') {
                this.orderCancelShow = false;
                this.yh_message_success('提交试算信息成功');
            } else {
                if (this.trailResultMsg.riskResult == '0') {
                    this.orderCancelShow = false;
                    this.handleClickButtonReset();

                    // 清空试算结果
                    this.trailResultMsg = {
                        calcTime: '',
                        takeTime: '',
                        riskResult: '',
                        riskResultTable: [],
                    };
                    const h = this.$createElement;
                    this.$message.success({
                        message: h('p', null, [
                            h('span', null, '本次风控下单结果为'),
                            h('span', { style: 'color: #70b603' }, '"合规"'),
                            h('span', null, '，已下单成功'),
                        ]),
                        showClose: true,
                        customClass: 'messageStyle',
                    });
                } else {
                    this.riskOrderResultAfterKey++;
                    this.orderCancelShow = true;
                }
            }
        });
    }

    // 试算按钮点击
    handleTestClick() {
        // 未点击“计算”按钮时
        if (!this.stockTableCalcState) {
            this.yh_message_warn('请先计算！');
            return;
        }
        this.orderCancelShow = false;
        this.handleSubmit('1');
    }

    /* ******************************** 试算、下单处理end *************************** */

    /* ************************************ 条目组设置start ********************************** */
    openEntryGroupDialog() {
        super.openEntryGroupDialog();
    }

    getEntryGroup(value: any) {
        super.getEntryGroup(value);
    }

    closeEntryDialog() {
        super.closeEntryDialog();
    }
    /* ************************************ 条目组设置end ********************************** */
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/risk-order';
</style>
<style lang="scss">
.messageStyle {
    background-color: #ecf9e3;
    border-color: #ecf9e3;
    font-size: 18px;
    .el-icon-success {
        color: #67c23a;
    }
}
</style>
